package tcss543.multiplehelpers;

import java.util.*;

import tcss543.*;

public class MultipleHelpersMatcherRandom implements Matcher {

	@Override
	public int[][] findMatching(DeviceGraph graph) {
		ObjectGraphBuilder ogb = new ObjectGraphBuilder();
		HashSet<Requestor> requestors0 = ogb.buildObjectGraph(graph);
		ArrayList<Requestor> requestors = new ArrayList<Requestor>(requestors0);
		
		ArrayList<Requestor> matchedRequestors = new ArrayList<Requestor>();
		
		Random rnd = new Random();
		
		while (!requestors.isEmpty()) {
			int selectedIndex = rnd.nextInt(requestors.size());
			Requestor requestor = requestors.remove(selectedIndex);
			ArrayList<Helper> candidateHelpers = new ArrayList<Helper>();
			for (int i = 0; i < requestor.neighbors.size(); i++) {
				if (!requestor.neighbors.get(i).used) {
					candidateHelpers.add(requestor.neighbors.get(i));
				}
			}
			
			ArrayList<Helper> helpers = new ArrayList<Helper>();
			int helperGroupCapacity = 0;
			while (!candidateHelpers.isEmpty()) {
				selectedIndex = rnd.nextInt(candidateHelpers.size());
				Helper helper = candidateHelpers.remove(selectedIndex);
				helpers.add(helper);
				helperGroupCapacity += helper.capacity;
				
				if (helperGroupCapacity >= requestor.unitsOfWork) {
					HelperGroup helperGroup = new HelperGroup();
					helperGroup.helpers = new ArrayList<Helper>();
					helperGroup.totalCapacity = helperGroupCapacity;
					for (int i = 0; i < helpers.size(); i++) {
						Helper h = helpers.get(i);
						h.used = true;
						helperGroup.helpers.add(h);
					}
					
					requestor.selectedHelperGroup = helperGroup;
					matchedRequestors.add(requestor);
					
					break;
				}
			}
		}
		
		int[][] requestorsAndGroups = new int[requestors0.size()][];
		
		for (Requestor r : matchedRequestors) {
			
			requestorsAndGroups[r.i] =
					new int[r.selectedHelperGroup.helpers.size()];
			for (int j = 0; j < requestorsAndGroups[r.i].length; j++) {
				requestorsAndGroups[r.i][j] = r.selectedHelperGroup.helpers.get(j).j;
			}
		}
		
		return requestorsAndGroups;
	}

}
